# -*- coding: utf-8 -*-
import uuid

from flask import Blueprint, render_template, request, jsonify
from common.models.user import User
from flask import Blueprint, request, jsonify, json
from application import db
import uuid
from operator import and_, __or__, or_
from common.libs.queryToDict import *
from datetime import datetime, date
import os

route_user = Blueprint('user_page', __name__)


# 用户登录
@route_user.route("/login", methods=["GET", "POST"])
def login():
    resp = {"err": "0", "errMsg": "登录成功", "data": ""}
    req = request.get_json()
    # 用户编码
    user_code = req['user_code'] if 'user_code' in req else ''
    # 用户密码
    password = req['password'] if 'password' in req else ''
    # 验证用户信息
    if user_code is None or len(user_code) < 1:
        resp['err'] = -1
        resp['errMsg'] = "请输入用户名！"
        return jsonify(resp)
    if password is None or len(password) < 1:
        resp['err'] = -1
        resp['errMsg'] = "请输入密码！"
        return jsonify(resp)
    # 根据用户密码查询用户信息
    user = User.query.filter(and_(User.user_code == user_code, User.password == password)).first()
    if user is None:
        resp['err'] = -1
        resp['errMsg'] = "用户名密码错误，请重新登录！"
        return jsonify(resp)

    resp['data'] = query_to_dict(user)
    return jsonify(resp)


@route_user.route("/register", methods=["GET", "POST"])
def register():
    in_vo = request.get_json()

    # 添加文章
    user = User()
    user.user_Id = uuid.uuid4()
    user.user_code = in_vo["user_code"]
    user_code = User.query.filter(User.user_code == user.user_code).first()
    if user_code:
        resp = {"err": "1", "errMsg": "用户名重复！", "data": ""}
        return jsonify(resp)

    user.user_name = in_vo["user_name"]
    user_name = User.query.filter(User.user_code == user.user_name).first()
    if user_name:
        resp = {"err": "1", "errMsg": "用户昵称重复！", "data": ""}
        return jsonify(resp)

    user.password = in_vo["password"]
    user.mobile = in_vo["mobile"]
    user.user_type = in_vo["user_type"]
    user.create_time = datetime.now()
    user.update_time = datetime.now()
    user.delflage = 0
    user.status = 1
    db.session.add(user)
    db.session.commit()
    resp = {"err": "0", "errMsg": "", "data": ""}
    return jsonify(resp)


@route_user.route("/edit")
def edit():
    return render_template("user/edit.html")


@route_user.route("/reset-pwd")
def reset_pwd():
    return render_template("user/reset_pwd.html")
